﻿using System.Text.RegularExpressions;
using ESSManageService.Common;
using ESSManageService.Common.Helper;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Serilog.Sinks.SystemConsole.Themes;
using Serilog;
using SqlSugar;
using SqlSugar.Extensions;
using SqlSugar.IOC;
using Microsoft.Extensions.Configuration;
using System.Configuration;
using ESSManageService.Services.DBServices;

namespace ESSManageService.Extensions
{
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlsugarSetup
    {
        public static IServiceCollection AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            // 配置 SqlSugarScope
            var sqlSugarScope = new SqlSugarScope(new ConnectionConfig
            {
                ConnectionString = AppSettings.GetValue("DBConnectionString").ToString(),
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });

            sqlSugarScope.Aop.OnLogExecuting = (sql, pars) =>
            {
                // 打印 SQL 语句和参数
                Console.WriteLine($"执行的 SQL 语句: {sql}");
                Console.WriteLine("参数:");
                foreach (var param in pars)
                {
                    Console.WriteLine($"  {param.ParameterName}: {param.Value}");
                }

                // 使用 Serilog 记录日志
                Log.Information("执行的 SQL 语句: {Sql}, 参数: {@Parameters}", sql, pars);
                /*Log.Information("SQL executed: {Sql} with parameters: {@Parameters}", sql, pars);*/
            };

            services.AddSingleton<ISqlSugarClient>(sqlSugarScope);

            return services;
        }
    }
}
